<template>
  <div>
    <base-modal
      :title="title"
      :show.sync="visible"
      width="480px"
      :close-on-click-modal="false"
      @close="handleClose"
    >
      <div class="deliver-goods-dialog">
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          
          label-position="top"
        >
          <el-form-item :label="$t('order.component.consignee')">
            {{ name }} {{ contactsPhone }}
          </el-form-item>
          <el-form-item class="form-address" :label="$t('order.component.shipToAddress')">
            <div>{{ address }}</div>
          </el-form-item>
          <el-form-item :label="$t('common.base.modeOfDespatch')" prop="deliveryMethod">
            <el-radio-group v-model="form.deliveryMethod" class="form-radio">
              <el-radio label="1" v-if="partsVersion" class="form-radio-item">{{
                '仓库发货'
              }}</el-radio>
              <el-radio label="3" v-else class="form-radio-item">{{
                '快递发货'
              }}</el-radio>
              <el-radio label="2" class="form-radio-item">{{$t('order.component.noNeedLogistics')}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <template v-if="form.deliveryMethod !== '2'">
            <el-form-item
              :label="$t('common.form.preview.sparepart.colum16')"
              prop="logisticsSource"
              v-if="partsVersion"
            >
              <el-radio-group v-model="form.logisticsSource" class="form-radio">
                <el-radio label="2" class="form-radio-item" :disabled="!state"
                  >{{$t('order.component.logisticsInfo')}}</el-radio
                >
                <el-radio label="1" class="form-radio-item">{{$t('goods.component.fillInManually')}}</el-radio>
              </el-radio-group>
            </el-form-item>
            <template v-if="form.logisticsSource === '1' || !partsVersion">
              <el-form-item :label="$t('common.base.logisticsCompany')" prop="logisticsCompany">
                <el-select
                  v-model="form.logisticsCompany"
                  :placeholder="$t('order.placeHolder.logisticsCompany')"
                  style="width: 80%"
                >
                  <el-option
                    v-for="item in logisticsCompanyList"
                    :key="item.expressId"
                    :label="item.expressName"
                    :value="item.expressName"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item :label="$t('common.base.logisticsNo')" prop="logisticsNumber">
                <el-input
                  v-model="form.logisticsNumber"
                  :placeholder="$t('common.validate.inputLogisticsNo')"
                  style="width: 80%"
                ></el-input>
              </el-form-item>
            </template>
          </template>
        </el-form>
        <div class="deliver-parcel" v-if="parcelList.length">
          <div>{{$t('order.component.associatedLogistics', {data1: parcelList.length})}}</div>
          <div v-for="(item, index) in parcelList" :key="item.logisticsNumber">
            <template v-if="item.shopLogisticsType === 1">
              {{ $t('order.component.packageText1', {data1: index + 1, logisticsCompany: item.logisticsCompany}) }}
              <span> {{ item.logisticsNumber }}</span>
            </template>
            <template v-else-if="item.shopLogisticsType === 2">
              {{ $t('order.component.packageText2', {data1: index + 1}) }}
            </template>
            <template v-else-if="item.shopLogisticsType === 3">
              {{ $t('order.component.packageText3', {data1: index + 1}) }}
            </template>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" @click="handleDeliver" :loading="loading"
          >{{$t('order.component.confirmDelivery')}}</el-button
        >
      </div>
    </base-modal>
  </div>
</template>

<script>
import _ from 'lodash';
import { getRootWindow } from '@src/util/dom';
import {
  queryOrderInfo,
  getSimpleLogistics,
  deliverGoods,
} from '@src/api/PortalApi.ts';
import { getExpressConfig } from '@src/api/LinkcApi';

export default {
  emits: ['reloadPage'],
  data() {
    return {
      visible: false,
      loading: false,
      name: '',
      contactsPhone: '',
      address: '',
      form: {
        deliveryMethod: '1',
        logisticsSource: '2',
        logisticsCompany: '',
        logisticsNumber: '',
      },
      rules: {
        deliveryMethod: [
          { required: true, message: this.$t('order.placeHolder.deliveryMethod'), trigger: 'change' },
        ],
        logisticsSource: [
          { required: true, message: this.$t('order.placeHolder.logisticsInfo'), trigger: 'change' },
        ],
        logisticsCompany: [
          { required: true, message: this.$t('order.placeHolder.logisticsCompany'), trigger: 'change' },
        ],
        logisticsNumber: [
          { required: true, message: this.$t('common.validate.inputLogisticsNo'), trigger: 'blur' },
        ],
      },
      logisticsCompanyList: [],
      parcelList: [],
      orderId: '',
      state: true,
    };
  },
  computed: {
    // 备件版本，灰度开启取备件3.0，没有开启取备件2.0
    partsVersion() {
      const RootWindow = getRootWindow(window);
      return RootWindow?.grayAuth?.cloudwarehouse ?? true;
    },
    title() {
      return this.partsVersion ? this.$t('goods.component.expressDelivery') : this.$t('order.component.goodsDelivery');
    },
  },
  methods: {
    open(id, state) {
      this.visible = true;
      this.orderId = id;
      // 如果true允许仓库物流发货
      this.state = state;
      if (!this.state) this.form.logisticsSource = '1';
      this.form.deliveryMethod = this.partsVersion ? '1' : '3';

      this.getOrderInfo();
      this.handleGetLogisticsCompany();
      this.handleGetParcelList();
    },
    async getOrderInfo() {
      try {
        const { code, data } = await queryOrderInfo({ orderId: this.orderId });

        if (code !== '200' || !data) {
          this.loading = false;
          return this.$message.error(this.$t('order.tips.queryOrderFailed'));
        }

        [this.name, this.contactsPhone, this.address] = [
          data?.name,
          data?.contactsPhone,
          data?.address,
        ];
      } catch (error) {
        console.error('fetch order info error', error);
      }
    },
    // 查询物流公司信息
    async handleGetLogisticsCompany() {
      try {
        const { code, data } = await getExpressConfig();

        if (code !== '200' || !data) {
          return this.$message.error(this.$t('order.tips.obtainlogistics'));
        }

        this.logisticsCompanyList = data || [];
      } catch (error) {
        console.error('fetch logistics company list error', error);
      }
    },
    // 查询已关联的物流包裹数
    async handleGetParcelList() {
      try {
        this.orderCorrelationServiceList = [];
        const { code, data } = await getSimpleLogistics({
          orderId: this.orderId,
        });

        if (code !== '200' || !data) {
          return this.$message.error(this.$t('order.tips.associatedLogistics'));
        }

        this.parcelList = data;
      } catch (error) {
        console.error('handleGetParcelList error', error);
      }
    },
    handleJumpDetail() {},
    handleClose() {
      this.visible = false;
      this.form = this.$options.data.call(this).form;
      this.$refs.formRef.clearValidate();
    },
    handleDeliver() {
      this.$refs.formRef.validate(async valid => {
        if (valid) {
          try {
            this.loading = true;
            const logisticsSource = this.partsVersion
              ? this.form.logisticsSource
              : '1';
            const params = {
              orderId: this.orderId,
              deliveryMethod: ~~this.form.deliveryMethod,
              logisticsSource: ~~logisticsSource,
              logisticsCompany: this.form.logisticsCompany,
              logisticsNumber: this.form.logisticsNumber,
            };
            const { code, msg } = await deliverGoods(params);

            if (code !== '200') {
              this.loading = false;
              return this.$message.error(msg || this.$t('order.tips.orderDeliveryFailed'));
            }

            this.$message.success(this.$t('order.tips.orderDeliverySucceeded'));
            this.loading = false;
            this.handleClose();
            this.$emit('reloadPage');
          } catch (error) {
            this.loading = false;
            console.error('order correlation service error', error);
          }
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.form-address {
  div {
    line-height: 24px;
    padding-top: 4px;
  }
}
.deliver-parcel {
  div {
    margin-bottom: 8px;
    color: #595959;
    font-size: 14px;
  }

  div:last-child {
    margin: 0;
  }

  span {
    color: $color-primary-light-6;
    cursor: pointer;
  }
}

.el-form-item {
  margin-bottom: 16px;
}
.deliver-goods-dialog {
  padding: 20px 30px;
}
</style>
